﻿using UnityEngine;
using System.Collections;
using System.Net;
using UnityEngine.Networking;

public class PlayerController : NetworkBehaviour
{
    public GameObject bulletPrefab;

    public Transform bulletSpwan;

    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }

        var x = Input.GetAxis("Horizontal")*Time.deltaTime*150.0f;
        var z = Input.GetAxis("Vertical")*Time.deltaTime*3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            CmdFire();
        }
    }

    [Command]
    private void CmdFire()
    {
        var bullet = (GameObject) Instantiate(bulletPrefab, 
            bulletSpwan.position, 
            bulletSpwan.rotation);

        var rigidbody = bullet.GetComponent<Rigidbody>();
        rigidbody.velocity = bullet.transform.forward*6;

        // 在其他客户端生成子弹
        NetworkServer.Spawn(bullet);

        Destroy(bullet, 2.0f);
    }

    public override void OnStartLocalPlayer()
    {
        var meshRenderer = GetComponent<MeshRenderer>();
        meshRenderer.material.color = Color.blue;
    }
}
